package com.budwk.app.sqfwV2.generator.weiqingmen;

import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CommonParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.ExcelGenerateParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.ExcelRowDataParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.BaseExcelGenerator;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.ResultOfExcelDataInto;
import com.budwk.app.sqfwV2.dto.weiqingmen.RectifyDTO;
import com.budwk.app.sqfwV2.dto.weiqingmen.SafetyCheckDTO;
import com.budwk.app.sqfwV2.dto.weiqingmen.SafetyCheckExcelImageConfigBO;
import com.budwk.app.sqfwV2.enums.weiqingmen.SafetyCheckEnum;
import com.budwk.app.util.ClassUtil;
import com.budwk.app.util.MapUtil;
import com.budwk.app.util.poiUtils.excelPictureConfigBO.ExcelFileCreateParamBO;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * @author 东方祥云低代码1.1
 * @since 2024-04-01
 * <p>
 * 威清门消防安全排查 SafetyCheck
 * 燃气排查周报表.xlsx
 */
public class GasSafetyExcelGenerator extends BaseExcelGenerator {

    /**
     * 自定义excel的表头数据
     *
     * @param excelParam         excel参数整体参数map
     * @param excelGenerateParam 创建excel所提供的参数
     */
    @Override
    protected void customerPopularHeaderData(Map<String, Object> excelParam, ExcelGenerateParam excelGenerateParam) {
        ExcelCreateConfig config = excelGenerateParam.getExcelConfig();
        // 是否为下载模板，如果为模板下载，则把标题的值设置为空
        if (config.getOnlyGenerateTemplateFlag()) {
            MapUtil.setMapValueToNull(excelParam);
        }
    }

    /**
     * 后端自定义维护表头数据
     *
     * @param excelParam         excel整体参数
     * @param excelGenerateParam 创建excel所提供的参数
     */
    @Override
    protected void customerPopularHeaderDataForAdmin(Map<String, Object> excelParam, ExcelGenerateParam excelGenerateParam) {

    }

    /**
     * 如果在遍历之前就能够判断excel是否生成，那么就在这个方法中进行判断(数据检测)
     * @param excelParam         excel整体参数
     * @param excelGenerateParam 创建excel所提供的参数
     * @return 判断excel是否含有数据
     */
    @Override
    protected ResultOfExcelDataInto judgeExcelHaveDataBeforeErgodic(Map<String, Object> excelParam, ExcelGenerateParam excelGenerateParam) {
        // 如果不是数据检测，直接返回
        if (excelGenerateParam.getExcelConfig().getCreateExcelFileFlag()) return null;

        // 数据检测
        List<ExcelRowDataParam> dataList = excelGenerateParam.getDataList();
        ResultOfExcelDataInto resultOfExcelDataInto = new ResultOfExcelDataInto();
        resultOfExcelDataInto.setExcelHaveDataFlag(false);
        for (ExcelRowDataParam excelRowDataParam : dataList) {
            // 判断是否有满足条件的数据，只有检测到一条就可以结束
            if (addRowDataCondition(excelRowDataParam, excelGenerateParam)) {
                resultOfExcelDataInto.setExcelHaveDataFlag(true);
                break;
            }
        }
        return resultOfExcelDataInto;
    }

    /**
     * 根据行数据判断是否该条数据进入excel中
     *
     * @param rowDataParam       行数据
     * @param excelGenerateParam excel生成所提供的参数
     * @return 是/否
     */
    @Override
    protected boolean addRowDataCondition(ExcelRowDataParam rowDataParam, ExcelGenerateParam excelGenerateParam) {
        SafetyCheckDTO fieldDTO = (SafetyCheckDTO) rowDataParam.getAbstractCustomerPdfCreateField();
        if (fieldDTO.getAttributesOfInspectionUnits() != null &&
                !fieldDTO.getAttributesOfInspectionUnits().contains("重点") &&
                !fieldDTO.getAttributesOfInspectionUnits().contains("危房") &&
                !fieldDTO.getAttributesOfInspectionUnits().contains("工地")) {
            return true;
        }
        return false;
    }

    /**
     * 用户自定义填充excel实体数据
     *
     * @param listMap            数据数据
     * @param excelGenerateParam 创建excel所需的参数
     */
    @Override
    protected void customerPopularSheetData(List<Map<String, Object>> listMap, ExcelGenerateParam excelGenerateParam) {
        listMap.clear();

        Map<String, Object> map = new HashMap<>();

        List<SafetyCheckDTO> safetyCheckList = (List<SafetyCheckDTO>) excelGenerateParam.getCustomerParamMap().get("safetyCheckList");

        CommonParam downloadUserParam = excelGenerateParam.getDownloadUserParam();
        map.put(ClassUtil.getField(CommonParam::getCounty), downloadUserParam.getCounty());

        List<ExcelRowDataParam> dataList = excelGenerateParam.getDataList();

        if (dataList.size() == 0) return;

        int manTime = 0;
        Set<String> checkFirm = new HashSet<>();
        int checkNum = 0;
        int total = 0;
        int normalTotal = 0;
        int greatTotal = 0;
        int normalChangeTotal = 0;
        int greatChangeTotal = 0;
        for (ExcelRowDataParam dataParam : dataList) {
            if (!addRowDataCondition(dataParam, excelGenerateParam)) continue;

            checkNum ++;
            SafetyCheckDTO fieldDTO = (SafetyCheckDTO) dataParam.getAbstractCustomerPdfCreateField();
            manTime += fieldDTO.getPeers().split(",").length;
            checkFirm.add(fieldDTO.getPlaceName() + fieldDTO.getAddress());
            normalTotal += getNormalTotal(fieldDTO);
            greatTotal += getGreatTotal(fieldDTO);
            normalChangeTotal += getNormalChangeTotal(fieldDTO, safetyCheckList);
            greatChangeTotal += getGreatChangeTotal(fieldDTO, safetyCheckList);
        }

        if (checkNum == 0) return;

        // 不能显示重大隐患数,重大隐患一致为0
        //total = normalTotal + greatTotal;
        total = normalTotal + 0;
        map.put("checkNum", checkNum);
        map.put("manTime", manTime);
        map.put("checkFirmNum", checkFirm.size());
        map.put("normalTotal", normalTotal);
        map.put("greatTotal", 0);
        map.put("total", total);
        map.put("normalChangeTotal", normalChangeTotal);
        map.put("greatChangeTotal", 0);

        listMap.add(map);
    }

    @Override
    protected void customerPopularRowDataMap(Map<String, Object> rowDataMap, ExcelRowDataParam rowDataParam) {

    }

    /**
     * 后端生成excel时候自定义填充excel中每一行的数据
     *
     * @param rowDataMap   当前行的数据Map
     * @param rowDataParam 所提供的当前行的数据
     */
    @Override
    protected void customerPopularRowDataMapForAdmin(Map<String, Object> rowDataMap, ExcelRowDataParam rowDataParam) {
        SafetyCheckDTO fieldDTO = (SafetyCheckDTO) rowDataParam.getAbstractCustomerPdfCreateField();
    }

    /**
     * 在创建之前判断excel中是否含有数据
     *
     * @param excelParam         创建之前excel中已经填充的数据
     * @param excelGenerateParam 所提供的excel创建的所需要的数据
     * @return 结果
     */
    @Override
    protected ResultOfExcelDataInto judgeExcelHaveDataBeforeCreate(Map<String, Object> excelParam, ExcelGenerateParam excelGenerateParam) {
//        ResultOfExcelDataInto resultOfExcelDataInto = new ResultOfExcelDataInto();
//
//        List<Map<String, Object>> listMap = (List<Map<String, Object>>) excelParam.get("list");
//
//        if (excelGenerateParam.getExcelConfig().getCreateExcelFileFlag()) return null;
//
//        // 数据检测
//        if (listMap != null && listMap.size() > 0) {
//            resultOfExcelDataInto.setExcelHaveDataFlag(true);
//        } else {
//            resultOfExcelDataInto.setExcelHaveDataFlag(false);
//        }
//        return resultOfExcelDataInto;
        return null;
    }

    @Override
    protected String getTemplatePath(ExcelGenerateParam excelGenerateParam) {
        return "sqfwV2/weiqingmen/GasSafety.xlsx";
    }

    /**
     * 可以参照 {@link com.budwk.app.sqfw.enums.DownLoadFileNameEnum}
     *
     * @return 文件名名称
     */
    @Override
    public String getDownloadFileName(ExcelGenerateParam excelGenerateParam) {
        //TODO 在这里返回你生成的文件名名称
        // 注意注意注意不用带上后缀
        return SafetyCheckEnum.GAS_SAFETY_INSPECTION.getCompilationName();
    }


    @Override
    protected Class<?> getImageConfigBO() {
        return SafetyCheckExcelImageConfigBO.class;
    }

    /**
     * 允许用户在创建excel文件之前对配置进行修改
     *
     * @param excelFileCreateParamBO 创建excel的配置参数
     */
    @Override
    protected void completeExcelFileCreateParam(ExcelFileCreateParamBO excelFileCreateParamBO) {

    }

    /**
     * 获取一般隐患数
     * @param fieldDTO
     * @return
     */
    private int getNormalTotal(SafetyCheckDTO fieldDTO) {
        List<RectifyDTO> recordsDTO = fieldDTO.getArrayOfFireSafetyPatrolRecords();
        List<RectifyDTO> bottledDTO = fieldDTO.getBottledGasProblemArray();

        int normalTotal = 0;

        // 消防安全隐患
        if (recordsDTO != null) {
            for (RectifyDTO rectifyDTO : recordsDTO) {
                if (StringUtils.isNotBlank(rectifyDTO.getRectificationDate()) && "一般".equals(rectifyDTO.getHiddenType())) {
                    normalTotal ++;
                }
            }
        }

        // 瓶装燃气隐患
        if (bottledDTO != null) {
            for (RectifyDTO rectifyDTO : bottledDTO) {
                if (StringUtils.isNotBlank(rectifyDTO.getRectificationDate()) && "一般".equals(rectifyDTO.getHiddenType())) {
                    normalTotal ++;
                }
            }
        }

        return normalTotal;
    }

    /**
     * 获取重大隐患数
     * @param fieldDTO
     * @return
     */
    private int getGreatTotal(SafetyCheckDTO fieldDTO) {
        List<RectifyDTO> recordsDTO = fieldDTO.getArrayOfFireSafetyPatrolRecords();
        List<RectifyDTO> bottledDTO = fieldDTO.getBottledGasProblemArray();

        int greatTotal = 0;

        // 消防安全隐患
        if (recordsDTO != null) {
            for (RectifyDTO rectifyDTO : recordsDTO) {
                if (StringUtils.isNotBlank(rectifyDTO.getRectificationDate()) && "重大".equals(rectifyDTO.getHiddenType())) {
                    greatTotal ++;
                }
            }
        }

        // 瓶装燃气隐患
        if (bottledDTO != null) {
            for (RectifyDTO rectifyDTO : bottledDTO) {
                if (StringUtils.isNotBlank(rectifyDTO.getRectificationDate()) && "重大".equals(rectifyDTO.getHiddenType())) {
                    greatTotal ++;
                }
            }
        }

        return greatTotal;
    }

    /**
     * 获取一般整改数
     * @param fieldDTO
     * @return
     */
    private int getNormalChangeTotal(SafetyCheckDTO fieldDTO, List<SafetyCheckDTO> safetyCheckDTOList) {
        // 获取离这次查询最近的下一次查询
        SafetyCheckDTO lastSafetyCheck = null;
        for (SafetyCheckDTO safetyCheckDTO : safetyCheckDTOList) {
            if ((fieldDTO.getPlaceName() == null || fieldDTO.getPlaceName().equals(safetyCheckDTO.getPlaceName())) &&
                    fieldDTO.getAddress().equals(safetyCheckDTO.getAddress()) &&
                    fieldDTO.getInspectionDate().getTime() < safetyCheckDTO.getInspectionDate().getTime()) {
                // 由于safetyCheckDTOList是按照升序查询排好序的，所以取到的第一条数据就是需要的数据
                lastSafetyCheck = safetyCheckDTO;
                break;
            }
        }

        int normalChangeTotal = 0;

        // 消防安全隐患
        if (fieldDTO.getArrayOfFireSafetyPatrolRecords() != null) {
            for (RectifyDTO rectifyDTO : fieldDTO.getArrayOfFireSafetyPatrolRecords()) {
                if ("一般".equals(rectifyDTO.getHiddenType()) && "现场整改".equals(rectifyDTO.getRectificationDate())) {
                    normalChangeTotal ++;
                }
            }
        }
        // 瓶装燃气隐患
        if (fieldDTO.getBottledGasProblemArray() != null) {
            for (RectifyDTO rectifyDTO : fieldDTO.getBottledGasProblemArray()) {
                if ("一般".equals(rectifyDTO.getHiddenType()) && "现场整改".equals(rectifyDTO.getRectificationDate())) {
                    normalChangeTotal ++;
                }
            }
        }

        if (lastSafetyCheck == null) {
            return normalChangeTotal;
        }

        // 最近的下一次
        List<RectifyDTO> lastRecordsDTO = lastSafetyCheck.getArrayOfFireSafetyPatrolRecords();
        List<RectifyDTO> lastBottledDTO = lastSafetyCheck.getBottledGasProblemArray();

        // 本次
        List<RectifyDTO> recordsDTO = fieldDTO.getArrayOfFireSafetyPatrolRecords();
        List<RectifyDTO> bottledDTO = fieldDTO.getBottledGasProblemArray();

        // 消防安全隐患（不分重大和一般，所以问题都是一般）
        if (recordsDTO != null && lastRecordsDTO != null) {
            for (int i = 0; i < recordsDTO.size(); i ++) {
                RectifyDTO rectifyDTO = recordsDTO.get(i);
                RectifyDTO lastRectifyDTO = lastRecordsDTO.get(i);
                if ("限期整改".equals(rectifyDTO.getRectificationDate()) && "现场整改".equals(lastRectifyDTO.getRectificationDate())) {
                    normalChangeTotal ++;
                }
            }
        }

        // 瓶装燃气隐患
        if (bottledDTO != null && lastBottledDTO != null) {
            for (int i = 0; i < bottledDTO.size(); i ++) {
                RectifyDTO rectifyDTO = bottledDTO.get(i);
                RectifyDTO lastRectifyDTO = lastBottledDTO.get(i);
                if ("一般".equals(rectifyDTO.getHiddenType()) && "限期整改".equals(rectifyDTO.getRectificationDate()) &&
                        "现场整改".equals(lastRectifyDTO.getRectificationDate())) {
                    normalChangeTotal ++;
                }
            }
        }

        return normalChangeTotal;
    }

    /**
     * 获取重大整改数(重大问题只有 瓶装燃气 才有)
     * @param fieldDTO
     * @return
     */
    private int getGreatChangeTotal(SafetyCheckDTO fieldDTO, List<SafetyCheckDTO> safetyCheckDTOList) {
        // 获取离这次查询最近的下一次查询
        SafetyCheckDTO lastSafetyCheck = null;
        for (SafetyCheckDTO safetyCheckDTO : safetyCheckDTOList) {
            if ((fieldDTO.getPlaceName() == null || fieldDTO.getPlaceName().equals(safetyCheckDTO.getPlaceName())) &&
                    fieldDTO.getAddress().equals(safetyCheckDTO.getAddress()) &&
                    fieldDTO.getInspectionDate().getTime() < safetyCheckDTO.getInspectionDate().getTime()) {
                // 由于safetyCheckDTOList是按照升序查询排好序的，所以取到的第一条数据就是需要的数据
                lastSafetyCheck = safetyCheckDTO;
                break;
            }
        }

        int greatChangeTotal = 0;

        // 瓶装燃气隐患
        if (fieldDTO.getBottledGasProblemArray() != null) {
            for (RectifyDTO rectifyDTO : fieldDTO.getBottledGasProblemArray()) {
                if ("重大".equals(rectifyDTO.getHiddenType()) && "现场整改".equals(rectifyDTO.getRectificationDate())) {
                    greatChangeTotal ++;
                }
            }
        }

        if (lastSafetyCheck == null) {
            return greatChangeTotal;
        }

        // 最近的下一次
        List<RectifyDTO> lastBottledDTO = lastSafetyCheck.getBottledGasProblemArray();

        // 本次
        List<RectifyDTO> bottledDTO = fieldDTO.getBottledGasProblemArray();

        // 瓶装燃气隐患
        if (bottledDTO != null && lastBottledDTO != null) {
            for (int i = 0; i < bottledDTO.size(); i ++) {
                RectifyDTO rectifyDTO = bottledDTO.get(i);
                RectifyDTO lastRectifyDTO = lastBottledDTO.get(i);
                if ("重大".equals(rectifyDTO.getHiddenType()) && "限期整改".equals(rectifyDTO.getRectificationDate()) &&
                        "现场整改".equals(lastRectifyDTO.getRectificationDate())) {
                    greatChangeTotal ++;
                }
            }
        }

        return greatChangeTotal;
    }
}
